import { getLogger } from '@gnlab/utils'
import config from '@/config'
import { setFavicon, setPageTitle } from '@/lib/title'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { usePageVisible } from './page-visible'

const logger = getLogger('ui/tab-unread-notice')

/**
 * 页面切到后台时，在标签页 favicon 和 title 中显示新增的未读消息数
 *
 * TODO: 处理异常情况，如果有企业微信退出，可能导致新统计到的未读数比原来少，想办法妥善处理
 * 例如每个企业微信分别统计？
 */
export default function useTabUnreadNotice() {
  const visible = usePageVisible()
  const [unreads] = useStreams(services.chat.metas.unreads)

  const baseUnreadsRef = useRef<number | null>(null)
  const newUnreads = useMemo(() => {
    if (visible) {
      // 前台状态，重置之前记录的初始未读消息数，且“新未读消息数”固定为 0
      baseUnreadsRef.current = null
      return 0
    } else {
      const currentUnreads = unreads.reduce((sum, item) => sum + item.unread, 0)
      if (baseUnreadsRef.current === null) {
        // 刚切到后台，记录初始未读消息数，这些消息数不统计到要通知的数量里
        baseUnreadsRef.current = currentUnreads
        return 0
      } else {
        // 返回自从切到后台后，增加了多少未读数（避免意外情况，最小返回 0）
        return Math.max(0, currentUnreads - baseUnreadsRef.current)
      }
    }
  }, [visible, unreads])

  const normalTitle = useMemo(() => {
    let title = document.title
    if (!title.startsWith(config.PRODUCT_NAME)) {
      logger.warn(`默认 title 不正常："${title}"`)
      title = config.PRODUCT_NAME
    }
    logger.info('recorded title: ' + title)
    return title
  }, [])

  useEffect(() => {
    if (newUnreads <= 0) {
      setFavicon(config.FAVICON_URL)
      setPageTitle(normalTitle)
    } else {
      setPageTitle(`(${newUnreads}) ` + normalTitle)

      let on = false
      const intervalId = setInterval(() => {
        setFavicon(on ? config.FAVICON_UNREAD_URL : config.FAVICON_URL)
        on = !on
      }, 500)
      return () => clearInterval(intervalId)
    }
  }, [newUnreads, normalTitle])
}
